﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace MediPlatform.Infeartructure
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private readonly MyDbContext _context;

        public BaseRepository(MyDbContext context)
        {
            _context = context;
        }

        public async Task<int> Create(T t)
        {
            try
            {
                await _context.Set<T>().AddAsync(t);
                return await _context.SaveChangesAsync();
            }
            catch (Exception)
            {
                throw;
            }
        }

        public async Task<T> AddAsync(T entity)
        {
            var entry = await _context.Set<T>().AddAsync(entity);
            return entry.Entity;
        }

        public async Task<IQueryable<T>> GetAll()
        {
            return _context.Set<T>();
        }

        public async Task<T> GetValue(long id)
        {
            return await _context.Set<T>().FindAsync(id);
        }

        public async Task<T?> GetAsync(Expression<Func<T, bool>> predicate)
        {
            return await _context.Set<T>().FirstOrDefaultAsync(predicate);
        }

        public IQueryable<T> Query()
        {
            return _context.Set<T>();
        }

        public async Task<int> Update(T t)
        {
            _context.Set<T>().Update(t);
            return await _context.SaveChangesAsync();
        }

        public void UpdateEntity(T entity)
        {
            _context.Set<T>().Update(entity);
        }

        public void Delete(T entity)
        {
            _context.Set<T>().Remove(entity);
        }

        public async Task<int> SaveChangesAsync()
        {
            return await _context.SaveChangesAsync();
        }
    }
}
